#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : bigDataProject 
@File    : mysql_control.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/11/10 15:56 
@Describe: MySQL封装
"""
from typing import Text, Any

import pymysql

from config.yaml_file_read import mysql_info_cfg
from utils.log.log_control import LogHandler


class MysqlControl:
    def __init__(self, db_name: Text) -> None:
        """
        构造函数
        :param db_name: 需要连接的数据库 如:member
        """
        self.logging = LogHandler().get_logger()
        try:
            self.conn = pymysql.connect(
                host=mysql_info_cfg['host'],
                port=mysql_info_cfg['port'],
                user=mysql_info_cfg[db_name]['user'],
                password=mysql_info_cfg[db_name]['password'],
                database=mysql_info_cfg[db_name]['database'],
                charset='utf8'
            )
            self.logging.debug("正在连接{}数据库".format(db_name))
            self.cursor = self.conn.cursor()
        except AttributeError as error:
            self.logging.error("数据库连接失败，失败原因:{}".format(error))

    def __del__(self) -> None:
        try:
            self.cursor.close()
            self.conn.close()
            self.logging.debug("Connection closed")
        except AttributeError as error:
            self.logging.error("关闭数据连接失败，失败原因:{}".format(error))

    def query_data(self, sql: Text, one: bool = False) -> Any:
        """
        查询数据
        :param sql:
        :param one: 是否查询单条数据，默认所有
        :return:
        """
        try:
            self.logger.info('正在执行查询数据操作,查询语句:[{}]'.format(sql))
            self.cursor.execute(sql)
            if one is False:
                data = self.cursor.fetchall()
            else:
                data = self.cursor.fetchone()
            self.logging.debug("查询数据成功，数据:{}".format(data))
            return data
        except AttributeError as error:
            self.logging.error("查询数据失败，失败原因:{}".format(error))
            raise

    def db_operate(self, sql: Text):
        """数据库操作(增删改)"""
        try:
            # 使用 execute 操作 sql
            rows = self.cursor.execute(sql)
            # 提交事务
            self.conn.commit()
            self.logging.info("已执行数据库操作。操作SQL:[{}],影响行数:[{}]".format(sql, rows))
            return rows
        except AttributeError as error:
            self.logging.error("数据库操作失败，正在进行回滚操作~操作SQL:[{}],错误信息:[{}]".format(sql, error))
            # 如果事务异常，则回滚数据
            self.conn.rollback()
            raise
